﻿using DeviceManagementLib;
using System;
using System.Linq;
using System.Management.Automation;

namespace DeviceManagementModule
{
    [Cmdlet(VerbsCommon.Get, "Device", DefaultParameterSetName = "ByInstanceId")]
    [OutputType(typeof(Device))]
    public class GetDeviceCmdlet : DeviceCmdletBase
    {
        [Parameter(Position = 1, ValueFromPipeline = true, ValueFromPipelineByPropertyName = true, ParameterSetName = "ByInstanceId")]
        public string InstanceId
        {
            get { return instanceId; }
            set { instanceId = value; }
        }

        [Parameter(Position = 1, ValueFromPipeline = true, ValueFromPipelineByPropertyName = true, ParameterSetName = "ByName")]
        public string Name
        {
            get { return name; }
            set { name = value; }
        }

        [Parameter(Position = 2, ValueFromPipeline = true, ValueFromPipelineByPropertyName = true)]
        public DeviceManagementLib.Win32.DeviceClass? Class
        {
            get { return @class; }
            set { @class = value; }
        }

        [Parameter]
        public SwitchParameter ShowNonpresentPresentDevices { get; set; }

        //-----------------------------------------------------------------------------------------

        protected override void BeginProcessing()
        {
            base.BeginProcessing();
        }

        protected override void ProcessRecord()
        {
            try
            {
                devices = GetDevice();
            }
            catch (Exception ex)
            {
                WriteError(new ErrorRecord(ex, "ErrorGettingDevices", ErrorCategory.ReadError, null));
                return;
            }

            if (!ShowNonpresentPresentDevices)
                devices = devices.Where(d => d.IsPresent);

            foreach (var device in devices)
            {
                WriteObject(device);
            }
        }

        protected override void EndProcessing()
        {
            base.EndProcessing();
        }
    }
}